<script>
import Header from './components/Header.vue'
import CartMain from './components/CartMain.vue'
import CartFooter from './components/CartFooter.vue'
export default {
    components: {
        //缩写
        Header,
        CartMain,
        CartFooter
    },
    data() {
        return {
            cartItems: [
                {
                    id: 1,
                    isSelected: true,
                    productName: '华为荣耀手机',
                    shopName: '商家A',
                    price: '2009.9',
                    num: 1,
                },
                {
                    id: 2,
                    isSelected: false,
                    productName: '新品休闲裤',
                    shopName: '商家B',
                    price: '180.00',
                    num: 1,
                },
                {
                    id: 3,
                    isSelected: true,
                    productName: '图书《Vue.js前端开发框架应用》',
                    shopName: '商家C',
                    price: '59.9',
                    num: 1,
                },
            ]
        }
    },
    computed: {
        selectedNum() {
            return this.cartItems.filter(function (item) {
                return item.isSelected == true;
            }).length;
        },
        totalPrice() {
            let total = 0;
            this.cartItems.forEach(function (item) {
                if (item.isSelected == true)
                    total += parseFloat(item.price) * item.num;
            })
            return total.toFixed(2);
        }
    },
    methods:{
        increase(id){
            
            this.cartItems.forEach(function (item) {
                if (item.id == id){
                    item.num++;
                    return;
                }
                    
            })
        },
        decrease(id){
            
            this.cartItems.forEach(function (item) {
                if (item.id == id){
                    if(item.num>1)
                        item.num--;
                    return;
                }
                    
            })
        },
        deleteItem(id){
            console.log('delete',id);
            this.cartItems = this.cartItems.filter(function (item) {
                return item.id != id;
            })
        },
    }
}
</script>

<template>
    <div class="content">
        <Header></Header>

        <CartMain :cartItems="cartItems" @increase="increase" @decrease="decrease" @deleteItem="deleteItem"></CartMain>

        <CartFooter :cartItems="cartItems" :selectedNum="selectedNum" :totalPrice="totalPrice" ></CartFooter>
    </div>

</template>

<style scoped></style>
